package com.zhengsr.wanandroid.mvp.present;

import android.util.Log;

import com.zhengsr.corelib.bean.ArticleCollectBean;
import com.zhengsr.corelib.bean.BannerBean;
import com.zhengsr.corelib.bean.BaseResponse;
import com.zhengsr.corelib.bean.CollectBean;
import com.zhengsr.corelib.bean.LoginBean;
import com.zhengsr.corelib.utils.CommonUtils;
import com.zhengsr.corelib.utils.CusUtils;
import com.zhengsr.corelib.utils.RxUtils;
import com.zhengsr.corelib.utils.SprefUtils;
import com.zhengsr.wanandroid.mvp.base.BasePresent;
import com.zhengsr.wanandroid.mvp.contract.ContractManager;
import com.zhengsr.wanandroid.mvp.model.DataManager;
import com.zhengsr.wanandroid.widget.CusSubscribe;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function3;

/**
 * Created by zhengshaorui
 * time: 2018/8/19
 */

public class HomePresent extends BasePresent<ContractManager.IHomeView> {
    private static final String TAG = "HomePresent";
    private int mCurrentPage = 0;
    private DataManager mDataManager;
    public static HomePresent create(ContractManager.IHomeView view){
        return new HomePresent(view);
    }

    private HomePresent(ContractManager.IHomeView view){
        mDataManager = DataManager.getInstance();
        mView = view;
        mView.showLoading();
        if (CommonUtils.isNetworkConnected()){
            startLoad();
        }else{
            mView.showError();
        }
    }

    public void reload(){
        mView.showLoading();
        if (CommonUtils.isNetworkConnected()){
            startLoad();
        }else{
            mView.showError();
        }
    }

    private void startLoad() {
        Observable<BaseResponse<LoginBean>> loginBeans = mDataManager.loginIn(mDataManager.getLoginName(),mDataManager.getLoginPassword());
        Observable<BaseResponse<List<BannerBean>>> bannerListObservable = mDataManager.loadBannerData();
        Observable<BaseResponse<ArticleCollectBean>> wanFeedListObservable = mDataManager.loadArticleList(mCurrentPage);


        Observable observable = Observable.zip(loginBeans, bannerListObservable, wanFeedListObservable, new Function3<
                BaseResponse<LoginBean>,
                BaseResponse<List<BannerBean>>,
                BaseResponse<ArticleCollectBean>,
                HashMap<String,Object>>() {
            @Override
            public HashMap<String, Object> apply(BaseResponse<LoginBean> loginbean, BaseResponse<List<BannerBean>> bannerbean, BaseResponse<ArticleCollectBean> articlebean) throws Exception {
                return loadDataToMap(loginbean,bannerbean.getData(),articlebean.getData().datas);
            }
        });




        addSubscribe((Disposable) observable.compose(RxUtils.rxScheduers())
                .subscribeWith(new CusSubscribe<Map<String,Object>>(mView,"startload fail",true) {

            @Override
            public void onNext(Map<String, Object> stringObjectMap) {
                BaseResponse<LoginBean> loginBeans = CusUtils.cast(stringObjectMap.get(CusUtils.DATA_LOGIN));
               // Log.d(TAG, "zsr --> onNext: "+loginBeans);
               // Log.d(TAG, "zsr --> onNext: "+ mDataManager.getLoginName()+" "+mDataManager.getLoginPassword());
                if (loginBeans.getErrorCode() == BaseResponse.SUCCESS){
                    Log.d(TAG, "zsr --> 自动登录成功");
                }else{
                    SprefUtils.saveSprefValue(SprefUtils.LOGIN_STATUS, false);
                    Log.d(TAG, "zsr --> 自动登录失败");
                }
                List<BannerBean> bannerDatas = CusUtils.cast(stringObjectMap.get(CusUtils.DATA_BANNER));
                List<CollectBean> articleDatas =  CusUtils.cast(stringObjectMap.get(CusUtils.DATA_ARTICLE));
                mView.loadSuccess();
                mView.loadDataSuccess(bannerDatas,articleDatas);
            }
        }));

    }

    private HashMap<String,Object> loadDataToMap(
            BaseResponse<LoginBean> loginBeans,
            List<BannerBean> bannerBeans,
            List<CollectBean> articleBeans){

        HashMap<String,Object> map = new HashMap<>();
        map.put(CusUtils.DATA_LOGIN,loginBeans);
        map.put(CusUtils.DATA_BANNER,bannerBeans);
        map.put(CusUtils.DATA_ARTICLE,articleBeans);
        return map;
    }

    public void onRefresh(){
        mCurrentPage = 0;
        startLoad();
    }

    /**
     * 加载更多
     * 页数自加
     */
    public void loadMore() {
        mCurrentPage++;
        addSubscribe(mDataManager.loadArticleList(mCurrentPage)
               .compose(RxUtils.<BaseResponse<ArticleCollectBean>>rxScheduers())
               .compose(RxUtils.<ArticleCollectBean>handleResult())
               .subscribeWith(new CusSubscribe<ArticleCollectBean>(mView, "load fail", false) {
                   @Override
                   public void onNext(ArticleCollectBean articlePageBean) {
                       mView.loadMoreData(articlePageBean.datas);
                   }
               }));
    }


    /**
     * 收藏站内文章
     */
    public void addCollectArticle(final int position, final CollectBean bean){

        addSubscribe(
                mDataManager.addCollectArticle(bean.getId())
                        .compose(RxUtils.<BaseResponse<ArticleCollectBean>>rxScheduers())
                        .subscribeWith(new CusSubscribe<BaseResponse<ArticleCollectBean>>(mView) {
                            @Override
                            public void onNext(BaseResponse<ArticleCollectBean> articleCollectBean) {
                                bean.setCollect(true);
                                mView.addCollectArticleSuccess(position,bean,articleCollectBean);
                            }
                        })
        );
    }

    public void cancelCollectArticle(final int position, final CollectBean bean){

        addSubscribe(
                mDataManager.cancelCollectArticle(bean.getId())
                        .compose(RxUtils.<BaseResponse<BaseResponse>>rxScheduers())
                        .subscribeWith(new CusSubscribe<BaseResponse<BaseResponse>>(mView) {
                            @Override
                            public void onNext(BaseResponse<BaseResponse> baseResponseBaseResponse) {
                                bean.setCollect(false);
                                mView.cancelCollectArticleSuccess(position,bean,baseResponseBaseResponse);
                            }
                        })
        );
    }



}
